let logger = require('./logger')
let config = require('./config')

let loginCount = 0

let http = function (app, wx) {
  return {
    get (option) {
      option.method = 'get'
      this.request(option)
    },
    post (option) {
      option.method = 'post'
      this.request(option)
    },
    request (option) {
      if (option.loading) {
        wx.showLoading({
          title: '加载中'
        })
      }
      let that = this
      wx.request({
        url: config.baseUrl + option.path,
        method: option.method,
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'token': app.globalData.token,
          'cityCode': app.globalData.cityCode
        },
        data: option.data,
        success (res) {
          if (option.loading) {
            wx.hideLoading()
          }
          
          if (option.success === undefined) {
            return
          }
          let result = res.data
          if (result.status === 'ok') {
            option.success(result.data)
          } else if (result.status === '601') {
            if (loginCount > 10) {
              return
            }
            logger.debug('token 过期,重新登录')
            loginCount++
            app.login({
              wx: wx,
              success() {
                logger.debug('重新登录成功, 重新调用业务请求')
                that.request(option)
                
              },
              complete() {
                loginCount--
                logger.debug('重新登录完成')
              }
            })
          } else {
            console.log(result)
            if (option.fail) {
              option.fail()
            }
            wx.showModal({
              title: '提醒',
              content: result.msg,
              showCancel: false,
              confirmText: '关闭'
            })
          }
          
        },
        fail () {
          if (option.loading) {
            wx.hideLoading()
          }
          
          if (option.fail === undefined) {
            wx.showToast({
              title: '网络繁忙',
              icon: 'loading',
              duration: 2000
            })
          } else {
            option.fail()
          }
        },
        complete () {
          if (option.complete) {
            option.complete()
          }
        }
      })
    }
  }
}
module.exports = http